

import 'dart:ffi';

import 'package:bt_tool/basic/bt_controller.dart';
import 'package:bt_tool/basic/bt_json_tool.dart';
import 'package:bt_tool/widget/bt_text_field.dart';

import 'json_preview_model.dart';

class JsonPreviewMainController extends BTController{

    final BTTextFieldController textFieldController = BTTextFieldController();
    List<JsonPreviewModel> dataList = [];

    @override
    void initState() {
        super.initState();
        textFieldController.onChanged = textDataChange;
    }

    textDataChange(String str){
        List<JsonPreviewModel> dataList = [];
        if(str.startsWith("{")){
            var map = BTJsonTool.convertStrToMap(str);
            JsonPreviewModel mapStartModel = JsonPreviewModel(null);
            mapStartModel.key = "{";
            mapStartModel.isCanOpen = true;
            dataList.add(mapStartModel);
            createJsonObjData(mapStartModel.childList, map, 0);
            JsonPreviewModel mapEndModel = JsonPreviewModel(null);
            mapEndModel.key = "}";
            dataList.add(mapStartModel);
        }
    }

    createJsonObjData(List<JsonPreviewModel> dataList, Map<String,dynamic> map, parentLevel){
        BTJsonTool jsonTool = BTJsonTool(map);
        int level = parentLevel + 1;
        for(var key in map.keys){
            JsonPreviewModel model = JsonPreviewModel(null);
            var obj = map[key];
            if(obj is Map<String,dynamic>){
                JsonPreviewModel modelMap = JsonPreviewModel(null);
                modelMap.key = "{";
                modelMap.isCanOpen = true;
                dataList.add(modelMap);
                createJsonObjData(dataList, obj, level);

            }else if(obj is List<dynamic>){

            }else{
                model.key = key;
                model.value = jsonTool.getString(key);
            }

            dataList.add(model);
        }
    }

}